package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.BumenEntity;
import com.java1234.entity.PageBean;
import com.java1234.entity.R;
import com.java1234.service.BumenService;
import com.java1234.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
* <p>
* 部门 前端控制器
* </p>
*
* @author Administrator
* @since 2025-05-09
*/
@RestController
@RequestMapping("/sys/bumen")
public class BumenController {

    @Autowired
    private BumenService service;

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:bumen:save')")
    public R save(@RequestBody BumenEntity entity){
        if(entity.getId()==null || entity.getId()==-1){
            entity.setAddtime(new Date());
            service.save(entity);
        }else{
            service.updateById(entity);
        }
        return R.ok();
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:bumen:list')")
    public R list(@RequestBody PageBean pageBean){
        String query = pageBean.getQuery() != null ? pageBean.getQuery().trim() : "";
        Page<BumenEntity> pageResult = service.page(
                new Page<>(pageBean.getPageNum(), pageBean.getPageSize()),
                new QueryWrapper<BumenEntity>()
                        .like(StringUtil.isNotEmpty(query), "bumen", query)
                        .orderByDesc("id") // 改为查询bumen字段而不是username
        );
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",pageResult.getRecords());
        resultMap.put("total",pageResult.getTotal());
        return R.ok(resultMap);
    }

    @PostMapping("/delete")
    @Transactional
    @PreAuthorize("hasAuthority('system:bumen:delete')")
    public R delete(@RequestBody Long[] ids){
        service.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @GetMapping("/info/{id}") // 添加这个接口匹配前端请求
    @PreAuthorize("hasAuthority('system:bumen:query')")
    public R info(@PathVariable(value = "id") Long id){
        BumenEntity entity = service.getById(id);
        Map<String,Object> map=new HashMap<>();
        map.put("bumen",entity); // 改为"bumen"匹配前端期望
        return R.ok(map);
    }

    @PostMapping("/all")
    @PreAuthorize("hasAuthority('system:bumen:all')")
    public R getAllBumen() {
        List<BumenEntity> list = service.list(new QueryWrapper<BumenEntity>().orderByDesc("id"));
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("list",list);
        resultMap.put("total",list.size());
        return R.ok(resultMap);
    }

}